<template>
  <div class="register-container">
    <el-card class="register-card" :body-style="{ padding: '40px' }">
      <template #header>
        <div class="card-header">
          <h2>用户注册</h2>
          <p>创建您的 AllHome 账号</p>
        </div>
      </template>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="0"
        size="large"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            :prefix-icon="Message"
            clearable
          />
        </el-form-item>

        <el-form-item prop="full_name">
          <el-input
            v-model="registerForm.full_name"
            placeholder="请输入真实姓名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="family_name">
          <el-input
            v-model="registerForm.family_name"
            placeholder="请输入家庭名称"
            :prefix-icon="House"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            style="width: 100%"
            :loading="authStore.isLoading"
            @click="handleRegister"
          >
            {{ authStore.isLoading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>

        <div class="form-footer">
          <el-checkbox v-model="agreeTerms">
            我已阅读并同意 <el-link type="primary">服务条款</el-link> 和 <el-link type="primary">隐私政策</el-link>
          </el-checkbox>
        </div>

        <div class="login-link">
          已有账号？
          <el-link type="primary" @click="$router.push('/login')">
            立即登录
          </el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { User, Lock, Message, House } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const registerFormRef = ref<FormInstance>()

// 表单数据
const registerForm = reactive({
  username: '',
  email: '',
  full_name: '',
  family_name: '',
  password: '',
  confirmPassword: ''
})

// 同意条款
const agreeTerms = ref(false)

// 密码确认验证
const validateConfirmPassword = (_rule: any, value: string, callback: any) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const registerRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  full_name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  family_name: [
    { required: true, message: '请输入家庭名称', trigger: 'blur' },
    { min: 2, max: 50, message: '家庭名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    
    if (!agreeTerms.value) {
      ElMessage.warning('请先同意服务条款和隐私政策')
      return
    }
    
    authStore.setLoading(true)
    authStore.clearError()

    // 调用注册API
    const registerData = {
      username: registerForm.username,
      email: registerForm.email,
      full_name: registerForm.full_name,
      family_name: registerForm.family_name,
      password: registerForm.password
    }
    
    const result = await authStore.register(registerData)
    
    if (result.success) {
      ElMessage.success('注册成功')
      router.push('/')
    } else {
      ElMessage.error(result.error || '注册失败')
    }

  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error('注册失败，请稍后重试')
  } finally {
    authStore.setLoading(false)
  }
}

// 组件挂载时检查是否已登录
onMounted(() => {
  if (authStore.isAuthenticated) {
    router.push('/')
  }
})
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 400px;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  margin-bottom: 20px;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.form-footer {
  margin-top: 20px;
}

.form-footer :deep(.el-checkbox__label) {
  font-size: 12px;
  color: #666;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-card {
    margin: 0 10px;
  }
  
  .card-header h2 {
    font-size: 20px;
  }
  
  .form-footer :deep(.el-checkbox__label) {
    font-size: 11px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .register-card {
    background: #1a1a1a;
    border-color: #333;
  }
  
  .card-header h2 {
    color: #fff;
  }
  
  .card-header p {
    color: #999;
  }
  
  .form-footer :deep(.el-checkbox__label) {
    color: #999;
  }
  
  .login-link {
    color: #999;
  }
}
</style>
